import { Component, inject, OnInit } from '@angular/core';
import { AbstractControl, AsyncValidatorFn, FormBuilder, FormControl, FormGroup, ValidationErrors, Validators } from '@angular/forms';
import { map, Observable, of } from 'rxjs';

import { CardRegex, CardRegexService } from '@app/core/services/http/card-regex/card-regex.service';
import { ValidatorsService } from '@app/core/services/validators/validators.service';
import { SharedModule } from '@app/shared/shared.module';
import { BasicConfirmModalComponent } from '@app/widget/base-modal';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NZ_MODAL_DATA, NzModalRef } from 'ng-zorro-antd/modal';

@Component({
  selector: 'app-card-regex-modal',
  standalone: true,
  imports: [SharedModule],
  templateUrl: './card-regex-modal.component.html',
  styleUrl: './card-regex-modal.component.less'
})
export class CardRegexModalComponent extends BasicConfirmModalComponent implements OnInit {
  isSpinningAdd: boolean = false;
  isEdit!: boolean;
  validateForm!: FormGroup;
  readonly nzModalData: CardRegex = inject(NZ_MODAL_DATA);
  private readonly fb: FormBuilder = inject(FormBuilder);
  private readonly messageService: NzMessageService = inject(NzMessageService);
  private readonly cardRegexService: CardRegexService = inject(CardRegexService);

  constructor(override modalRef: NzModalRef) {
    super(modalRef);
  }

  protected getCurrentValue(): Observable<NzSafeAny> {
    if (!this.validateForm.valid) {
      return of(false);
    }
    return of({ ...this.validateForm.value });
  }

  cardNameDuplicateValidate: AsyncValidatorFn = (control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> => {
    if (!control.value) {
      return Promise.resolve({ required: true });
    }

    let filterParams = `eq(CardName,${control.value})`;
    if (this.nzModalData?.id) {
      filterParams += `&noteq(Id,${this.nzModalData.id})`;
    }

    return this.cardRegexService.getEntityList({ '@filter': `${filterParams}` }).pipe(
      map(exist => {
        if (exist.length > 0) {
          const validationErrors: ValidationErrors = { duplicate: exist, message: '规则已存在' };
          return validationErrors;
        }

        return null;
      })
    );
  };

  initForm(): void {
    this.validateForm = this.fb.group({
      regexexpression: new FormControl('', {
        validators: [Validators.required]
      })
    });

    if (this.nzModalData) {
      this.validateForm.patchValue({ ...this.nzModalData });
    }
  }

  ngOnInit(): void {
    this.initForm();
    this.isEdit = !!this.nzModalData;
  }
}
